<!-- 订单-预约订单 -->
<template>
	<view class="page-box">

		<view class="order-box">
			<u-tabs class="order-box-t" activeStyle="color: #E27C8A;fontSize: 32rpx" lineHeight="6" lineColor="#E27C8A"
				inactiveStyle="color: #0F0D21;fontSize: 32rpx" :list="statusList" @change="handleSearch"></u-tabs>
			<view class="main-box">
				<noData style="margin-top: 200rpx;" v-if="!dataList.length"></noData>
				<template v-else>
					<view class="item" v-for="(item,index) in dataList" @tap="handleBtn(item,6)" :key="index">

						<view class="item-t">
							<image class="image" :src="item.coverUrl" @tap.stop="handleImg(item)"></image>

							<view class="item-c">
								<view class="aaa">

									<view class="ccc">
										<text class="item-c-name">{{item.stageName}}</text>
										<view class="scoreIcon">
											<image src="/static/images/scoreIcon.png"></image>
											<text>{{`评分 ${item.evaluateLevel || '5.0'}`}}</text>
										</view>
									</view>
									<image v-if="item.status == 1 || item.status == 2" @tap.stop="handleCall(item)"
										style="width: 52rpx;height: 52rpx;" src="/static/images/callIcon.png">
									</image>
								</view>

								<text class="item-c-time">
									{{`预约时间：${dayjs(item.subscribeStartTime).format('YYYY-MM-DD HH:mm')}~${dayjs(item.subscribeEndTime).format('HH:mm')}`}}
								</text>

								<view class="iii-box">
									<view class="box-item">
										<text class="box-item-title">称呼</text>
										<text class="box-item-text">{{item.salutation}}</text>
									</view>
									<view class="box-item">
										<text class="box-item-title">时长</text>
										<text class="box-item-text">{{item.duration + item.unit}}</text>
									</view>
									<view class="box-item">
										<text class="box-item-title">项目</text>
										<text class="box-item-text">{{item.categoryName}}</text>
									</view>
									<view class="box-item">
										<text class="box-item-title">金额</text>
										<text class="box-item-text money">￥{{item.payAmount}}</text>
									</view>

								</view>

							</view>
						</view>
						<view class="item-b">
							<!-- <text style="color: #0F0D21;font-size: 18rpx;background: rgba(0,0,0,0.1);
					border-radius: 8rpx;height: 34rpx;line-height: 34rpx;padding: 0 8rpx;">{{item.categoryName}}</text> -->
							<text class="item-b-status">{{item.statusName || ''}}</text>
							<view class="btn-box">
								<!-- <text class="box box-1" v-if="item.status === 0 && item.userId === userInfo.id" -->
								<!-- <text class="box box-1" v-if="item.status === 0"
									@tap.stop="handleBtn(item,0)">支付</text> -->
								<!-- && item.userId === userInfo.id @click="open"-->
								<button class="box box-1" v-if="item.status === 0 && item.userId === userInfo.id"
									@tap.stop="handlePopOpen()">支付</button>


								<text class="box box-2"
									v-if="(item.status === 3 || item.status === 5 || item.status === 4 || item.status === 6) && item.userId === userInfo.id"
									@tap.stop="handleBtn(item,4)">再次预约</text>


								<text class="box box-1"
									v-if="item.status === 1 && (item.artistId === userInfo.artistId || item.managerId === userInfo.id)"
									@tap.stop="handleBtn(item,1)">开始服务</text>
								<text class="box box-1"
									v-if="item.status === 2 && (item.artistId === userInfo.artistId || item.managerId === userInfo.id)"
									@tap.stop="handleBtn(item,2)">结束服务</text>
								<text class="box box-1"
									v-if="item.status === 7 && (item.artistId === userInfo.artistId || item.managerId === userInfo.id)"
									@tap.stop="handleBtn(item,7)">接单</text>
								<text class="box box-2"
									v-if="item.status === 1 && (item.artistId === userInfo.artistId || item.managerId === userInfo.id)"
									@tap.stop="handleBtn(item,3)">确认退款</text>


								<text class="box box-1" v-if="item.status === 3 && item.userId === userInfo.id"
									@tap.stop="handleBtn(item,5)">评价</text>

								<text class="box box-1"
									v-if="(item.status === 1 || item.status === 2) && (item.userId  === userInfo.id) && item.addHour === 0"
									@tap.stop="handleBtn(item,8)">续时</text>

							</view>
						</view>
						<!-- <view @touchmove.stop.prevent="disabledScroll"> -->
						<uni-popup ref="popup" @touchmove.stop.prevent="stopPrevent" type="bottom" bgColor=''
							@maskClick="handlePopClose()">
							<view class="form-box">
								<view class="">
									<radio-group @change="radioChange" @click.stop="stopPrevent" class="recharg-box">
										<view v-for="(item, index) in rechargTypeList" :key="item.code"
											class="recharg-box-c">
											<image :src="item.img"></image>
											<text class="recharg-item">{{item.type}}</text>
											<radio class="radio" color="#F7A254" :value="item.code"
												:checked="index === current" />
											<view class="type-bord" v-if="index == 0"></view>
										</view>
									</radio-group>
								</view>
							</view>
							<text class="recharg-btn-box" @tap.stop="handleBtn(item,0)">支付</text>
						</uni-popup>
						<!-- </view> -->
					</view>
				</template>

				<!-- 下拉刷新 -->
				<uni-load-more v-if="dataList.length > 0" :status="loadingType"></uni-load-more>

			</view>
		</view>
		<u-modal :show="show" title="请对艺人进行评价" :showCancelButton="true" cancelText="取消" :closeOnClickOverlay="true"
			@close="() => {description = '';show = false}" @cancel="() => {description = '';show = false}"
			@confirm="handleConfirm">
			<view class="slot-content">
				<uni-rate v-model="score" margin="12" :allowHalf="true" activeColor="#EC606F" :is-fill="false"
					@change="onChange" />
				<u--textarea v-model.trim="description" focus placeholder="请对艺人进行评价" placeholderStyle="color:#8C8A8A;">
				</u--textarea>
			</view>
		</u-modal>


		<!-- 弹出层-延时选择 -->
		<DelayTime :show="addTimeShow" :unit="addTimeSubmitUnit" :orderNo="addTimeSubmitId" @close="addTimeClose"
			@locationReload="locationReload"></DelayTime>

	</view>
</template>

<script>
	import noData from '@/components/noData/noData.vue'
	import dayjs from 'dayjs'
	import cookie from '@/utils/cookie.js'
	import {
		postOrderList,
		postOrderUpdate,
		getRefund,
		postEvaluate,
		postOrderPay,
	} from '@/api/order.js'
	import {
		mapState,
		mapGetters,
		mapMutations,
		mapActions
	} from 'vuex'


	// 页面组件
	import DelayTime from './components/delayTime.vue' // 延时组件

	export default {
		name: 'order',
		components: {
			noData,
			DelayTime // 延时组件
		},
		computed: {
			...mapGetters(['userInfo']),
		},
		data() {
			return {

				loadingType: 'loading', // 是否显示更多

				addTimeShow: false,
				addTimeSubmitId: 0, // 订单号
				addTimeSubmitUnit: '', // 续时的单位



				show: false,
				curInfo: {},
				description: '',
				score: 5,
				statusList: [{
						name: '全部',
						value: 999
					}, {
						name: '待付款',
						value: 0
					},
					{
						name: '待接单',
						value: 7
					}, {
						name: '待服务',
						value: 1
					}, {
						name: '进行中',
						value: 2
					}, {
						name: '已完成',
						value: 3
					}, {
						name: '已退款',
						value: 4
					},
					{
						name: '已取消',
						value: 5
					},
					{
						name: '已评价',
						value: 6
					},
				],
				dataList: [],
				queryState: {
					pageNum: 1,
					pageSize: 10,
					total: 0,
					isQuery: true,
					status: 999
				},
				rechargType: 'wx',
				isShowPop: false,
				rechargTypeList: [{
					type: '微信',
					code: 'wx',
					img: '../../static/images/wxPay.png'
				}, {
					type: '余额',
					code: 'balance',
					img: '../../static/images/balancePay.png'
				}],
				current: 0
			};
		},

		onShow() {
			this.handleXXX()
		},
		async onPullDownRefresh() {
			await this.handleXXX()
			uni.stopPullDownRefresh()
			uni.showToast({
				duration: 5000,
				title: '刷新成功',
				icon: 'none'
			})
		},
		async onReachBottom() {
			if (!this.queryState.isQuery) return false
			this.queryState.pageNum++
			await this.handleInit()
		},
		methods: {
			dayjs,

			...mapMutations('home', ['setOrderItemData']),

			/**
			 * 刷新页面
			 */
			locationReload() {
				console.log('舒心页面');
				location.reload()
			},

			onChange(e) {
				console.log('rate发生改变:' + JSON.stringify(e), this.score)
				// console.log(this.score);
			},
			open: function() {
				this.$refs.popup[0].open()
			},
			close: function() {
				this.$refs.popup[0].close()
				event.stopPropagation();
			},
			handleImg(e) {
				this.handleTo(
					`/pages/artist/info?id=${e.artistId}`
				)
			},
			handleTo(url) {
				uni.navigateTo({
					url
				})
			},
			handleCall({
				contactPhone,
				managerPhone,
				artistId,
				userId
			}) {
				const phone = userId === this.userInfo.id ? managerPhone : contactPhone
				if (!phone) return uni.showToast({
					duration: 5000,
					icon: 'none',
					title: '拨打失败，拨打手机号不存在'
				});
				location.href = `tel:${phone}`;
			},
			wxAppFn(params) {
				const that = this
				WeixinJSBridge.invoke('getBrandWCPayRequest', params, function(res) {
					that.handleXXX()
					if ('get_brand_wcpay_request:ok' === res.err_msg) {
						uni.showToast({
							duration: 2000,
							icon: 'none',
							title: '支付成功'
						})
						location.reload()
						// that.handlePay('success')
						// 使用以上方式判断前端返回,微信团队郑重提示：
						// res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
						// alert('get_brand_wcpay_request:ok')
					} else if (res.err_msg === 'get_brand_wcpay_request:cancel' || res.err_msg ===
						'get_brand_wcpay_request:fail') {
						uni.showToast({
							duration: 5000,
							icon: 'none',
							title: '支付失败'
						})
						location.reload()
						// that.handlePay('error')
					} else {
						uni.showToast({
							duration: 5000,
							icon: 'none',
							title: '支付失败'
						})
						location.reload()
						// that.handlePay('error')
					}
				})
			},
			handleXXX() {
				Object.assign(this.queryState, {
					pageNum: 1
				})

				// loading状态
				this.loadingType = 'loading'

				this.handleInit()
			},
			handlePay(type) {
				if (type === 'success') {
					this.handleXXX()
					// this.$store.dispatch('paymentQuery')
				} else if (type === 'error') {
					this.handleXXX()
				}
			},
			handlePopOpen() {
				this.open();
			},
			handlePopClose() {
				this.close();
			},
			stopPrevent() {},
			radioChange: function(evt) {
				for (let i = 0; i < this.rechargTypeList.length; i++) {
					if (this.rechargTypeList[i].code === evt.detail.value) {
						this.current = i;
						this.rechargType = this.rechargTypeList[i].code;
						break;
					}
				}
			},
			handleBtn(e, type) {
				const that = this
				if (type === 0) {
					if (!this.rechargType) return uni.showToast({
						duration: 5000,
						title: '请选择支付方式',
						icon: 'none'
					})
					uni.showLoading({
						title: '正在处理中'
					});
					//支付方式：0-余额；1-微信；2-支付宝
					postOrderPay({
						orderId: e.id,
						payType: that.rechargType == 'balance' ? 0 : 1
					}).then(res => {
						if (res.code !== 200) {
							uni.showToast({
								duration: 3000,
								icon: 'none',
								title: res.msg || '请求失败'
							})
							setTimeout(() => {
								location.reload()
							}, 3000)
							return
						}
						//支付方式：0-余额；1-微信；2-支付宝
						if (that.rechargType == 'balance') {
							uni.showToast({
								duration: 2000,
								icon: 'none',
								title: '支付成功'
							})
							setTimeout(() => {
								location.reload()
							}, 2000)
							return
							// that.handlePay('success')
							// that.handlePopClose()
						}
						const payConfig = res.data.result.jsConfig
						const params = {
							appId: payConfig.appId,
							timeStamp: payConfig.timestamp,
							nonceStr: payConfig.nonceStr,
							package: payConfig.package,
							signType: payConfig.signType,
							paySign: payConfig.paySign
						}

						// if (this.rechargType == 'balance') {
						// 	this.balancePayFn(payConfig.orderNo)
						// } else
						if (typeof WeixinJSBridge == "undefined") {
							if (document.addEventListener) {
								document.addEventListener('WeixinJSBridgeReady', this.wxAppFn(params), false)
							} else if (document.attachEvent) {
								document.attachEvent('WeixinJSBridgeReady', this.wxAppFn(params))
								document.attachEvent('onWeixinJSBridgeReady', this.wxAppFn(params))
							}
						} else {
							this.wxAppFn(params)
						}
					}).finally(() => {
						uni.hideLoading();
					})
				} else if (type === 1 || type === 2) {
					uni.showModal({
						title: `请确认是否${type === 1 ? '开始' : '结束'}服务？`,
						success: function(res) {
							if (res.confirm) {
								uni.showLoading({
									title: '正在处理中'
								});
								postOrderUpdate({
									orderNo: e.orderNo,
									operation: type
								}).then((res) => {
									if (res.code !== 200) {
										uni.showToast({
											duration: 5000,
											icon: 'none',
											title: res.msg || '请求失败'
										})
										return
									}
									uni.showToast({
										duration: 5000,
										icon: 'none',
										title: '操作成功'
									})
									that.handleXXX()
								}).catch(({
									message: title = '操作失败'
								}) => {
									uni.showToast({
										duration: 5000,
										icon: 'none',
										title
									})
								}).finally(() => {
									uni.hideLoading();
								})
							} else if (res.cancel) {}
						}
					});

				} else if (type === 3) {
					uni.showModal({
						title: '请确认是否退款？',
						success: function(res) {
							if (res.confirm) {
								uni.showLoading({
									title: '正在处理中'
								});
								getRefund(e.orderNo).then((res) => {
									if (res.code !== 200) {
										uni.showToast({
											duration: 5000,
											icon: 'none',
											title: res.msg || '请求失败'
										})
										return
									}
									uni.showToast({
										duration: 5000,
										icon: 'none',
										title: '操作成功'
									})
									that.handleXXX()
								}).catch(({
									message: title = '操作失败'
								}) => {
									uni.showToast({
										duration: 5000,
										icon: 'none',
										title
									})
								}).finally(() => {
									uni.hideLoading();
								})
							} else if (res.cancel) {}
						}
					});
				} else if (type === 4) {
					uni.navigateTo({
						url: `/pages/order/placeOrder?artistId=${e.artistId}&categoryId=${e.categoryId}&duration=${e.duration}&address=${e.address}&cityCode=${e.cityCode}&cityName=${e.cityName}&salutation=${e.salutation}&contactPhone=${e.contactPhone}&isRest=1`
					})
				} else if (type === 5) {
					that.show = true
					that.curInfo = e
				} else if (type === 6) {
					cookie.set('placeOrder', 1)

					// 艺人中心里面的订单管理详情，只有一个展示作用，并且人工处理过展示数据，所以阅读性比较好
					this.setOrderItemData(e)
					uni.navigateTo({
						url: '/pages/artist/artistCentre/orderManage/OrderDetails/index'
					});
				} else if (type === 7) {
					uni.showModal({
						title: `请确认是否接单？`,
						success: function(res) {
							if (res.confirm) {
								uni.showLoading({
									title: '正在处理中'
								});
								postOrderUpdate({
									orderNo: e.orderNo,
									operation: 3
								}).then((res) => {
									if (res.code !== 200) {
										uni.showToast({
											duration: 5000,
											icon: 'none',
											title: res.msg || '请求失败'
										})
										return
									}
									uni.showToast({
										duration: 5000,
										icon: 'none',
										title: '操作成功'
									})
									that.handleXXX()
								}).catch(({
									message: title = '操作失败'
								}) => {
									uni.showToast({
										duration: 5000,
										icon: 'none',
										title
									})
								}).finally(() => {
									uni.hideLoading();
								})
							} else if (res.cancel) {}
						}
					});

				}


				// 续时
				if (type === 8) {
					this.addTimeShow = true // 显示选择续时时间弹窗
					console.log(e, 'kkkkk', e.orderNo);
					this.addTimeSubmitId = e.orderNo // 订单id
					this.addTimeSubmitUnit = e.unit // 订单延时单位

				}


			},

			/**
			 * 关闭延时的弹窗
			 */
			addTimeClose() {
				this.addTimeShow = false
			},


			handleConfirm() {
				const {
					id: orderId
				} = this.curInfo

				console.log(this.curInfo, '11kkkkkkkkkkkk');

				uni.showLoading({
					title: '正在处理中'
				});
				postEvaluate({
					description: this.description,
					score: this.score,
					orderNo: this.curInfo.orderNo
				}).then((res) => {
					if (res.code !== 200) {
						uni.showToast({
							duration: 5000,
							icon: 'none',
							title: res.msg || '请求失败'
						})
						return
					}
					uni.showToast({
						duration: 5000,
						icon: 'none',
						title: '评价成功'
					})
					this.description = ''
					this.show = false
					this.handleXXX()
				}).catch(({
					message: title = '操作失败'
				}) => {
					uni.showToast({
						duration: 5000,
						icon: 'none',
						title
					})
				}).finally(() => {
					uni.hideLoading();
				})
			},
			async handleInit() {
				const {
					pageNum,
					pageSize,
					status
				} = this.queryState
				const params = {
					pageNum,
					pageSize,
					status: status === 999 ? null : status
				}
				try {
					uni.showLoading({
						title: '正在加载中'
					});
					const {
						rows,
						total,
					} = await postOrderList(params)

					if (rows.length < pageSize) {
						this.loadingType = 'noMore'
					}

					if (pageNum === 1) this.dataList = []
					this.dataList = this.dataList.concat(rows)

					Object.assign(this.queryState, {
						isQuery: this.dataList.length < total,
						total
					})
				} catch ({
					message: title = '获取订单列表失败'
				}) {
					Object.assign(this.queryState, {
						isQuery: false
					})
					uni.showToast({
						duration: 5000,
						icon: 'none',
						title
					})

				} finally {
					uni.hideLoading();
				}
			},
			handleSearch({
				value
			}) {
				this.queryState.status = value
				this.handleXXX()
			}
		}
	}
</script>

<style lang="less" scoped>
	.page-box {
		position: relative;
		box-sizing: border-box;
		#padding(24rpx 0 0 0);
		background: linear-gradient(180deg, rgba(238, 212, 215, 0.8) -3%, rgba(202, 191, 192, 0) 100%);
		min-height: 100vh;
	}

	.order-box {
		position: absolute;
		top: 0;
		width: 100%;
		display: flex;
		flex-direction: column;

		.order-box-t {
			position: sticky;
			top: 0;
			z-index: 2;

			// .box {
			// 	width: 25%;
			// 	text-align: center;
			// 	color: #0F0D21;
			// 	font-size: 32rpx;
			// 	font-weight: bold;

			// 	&-select {
			// 		background: linear-gradient(180deg, #E27C8A 0%, #EC606F 100%);
			// 		-webkit-background-clip: text;
			// 		-webkit-text-fill-color: transparent;

			// 		position: relative;

			// 		&::before {
			// 			position: absolute;
			// 			content: '';
			// 			width: 56rpx;
			// 			height: 8rpx;
			// 			opacity: 1;
			// 			background-color: #E27C8A;
			// 			border-radius: 4rpx;
			// 			left: 50%;
			// 			transform: translateX(-50%);
			// 			bottom: -36rpx;
			// 		}
			// 	}
			// }

		}

		.main-box {
			margin-bottom: 24rpx;

			.recharg-btn-box {
				// position: fixed;
				margin: 0 30rpx 32rpx 30rpx;
				display: flex;
				flex-direction: column;
				width: 682rpx;
				height: 88rpx;
				line-height: 88rpx;
				text-align: center;
				background: linear-gradient(180deg, #E27C8A 0%, #EC606F 100%);
				border-radius: 40rpx;
				color: #FDF3F3;
				font-size: 36rpx;
			}

			.form-box {
				width: 682rpx;
				margin: 30rpx 30rpx 32rpx 40rpx;
				border-radius: 40rpx;
				box-sizing: border-box;
				display: flex;
				flex-direction: column;
				padding: 24rpx 40rpx;
				border-radius: 40rpx;
				background: #FFFFFF;
				box-shadow: 0px 0px 16rpx 6rpx rgba(210, 211, 213, 0.5);

				.recharg-box {
					display: flex;
					width: 100%;
					justify-content: space-between;
					padding-left: 20rpx;
					padding-right: 20rpx;

					.recharg-box-c {
						width: 50%;
						display: flex;
						align-items: center;
						justify-content: left;
						// justify-content: space-between;

						&>text {
							padding-right: 70rpx;
							font-size: 28rpx;
							color: #0F0D21;
						}

						&>image {
							width: 40rpx;
							height: 40rpx;
							padding-right: 20rpx;
							// left: 20rpx;
						}

						.type-bord {
							&::after {
								content: "";
								flex: 1 1;
								border-right: 3rpx solid #D9D9D9;
								margin: auto;
								padding-left: 40rpx;
							}
						}

						.radio {
							transform: scale(0.7);
						}

					}


					.recharg-item {
						line-height: 128rpx;
						text-align: left;
						color: #0F0D21;
						font-size: 32rpx;


						&-s {
							color: #EC606F;
						}

						&-p {
							border: 2rpx solid #EC606F;
						}
					}
				}

			}

			.item {
				margin: 24rpx 32rpx 0 32rpx;
				#padding(16rpx 24rpx);
				#box(-, -, 16rpx, #fff);
				box-shadow: 0px 0px 16rpx 6rpx rgba(210, 211, 213, 0.5);

				.item-c {
					flex: 1;

					.item-c-name {
						#font(36rpx, #0f0d21, 600);
					}

					.scoreIcon {
						#font(22rpx, #0f0D21, black);
						#flex(-, -, center);

						image {
							#box(32rpx);
							margin: 0 8rpx 0 24rpx;
						}
					}

					.item-c-time {
						#font(24rpx, #8c8a8a);
						margin: 16rpx 0;
					}


				}

				.item-t {
					display: flex;
					flex-direction: row;
					padding-bottom: 16rpx;
					border-bottom: 2rpx solid rgba(0, 0, 0, 0.1);
					margin-bottom: 16rpx;

					.image {
						#box(120rpx, 120rpx, 100%);
						margin-right: 24rpx;
					}
				}

				.item-b {
					display: flex;
					align-items: center;
					justify-content: space-between;

					.item-b-status {
						#font(28rpx, #ec606f);

					}

					.btn-box {
						display: flex;

						.box {
							height: 52rpx;
							line-height: 52rpx;
							border-radius: 26rpx;
							padding: 0 24rpx;
							font-size: 24rpx;
							font-weight: bold;

							margin-right: 16rpx;

							&:last-child {
								margin-right: 0;
							}

							&-1 {
								color: #FDF3F3;
								background: linear-gradient(180deg, #E27C8A 0%, #EC606F 100%);
							}

							&-2 {
								border: 2rpx solid rgba(0, 0, 0, 0.1);
								color: #0F0D21;
							}
						}

					}
				}

				.aaa {
					#flex(-, space-between, center);
					margin-top: 20rpx;

					.ccc {
						#flex(-, -, center);
					}
				}
			}


		}
	}

	::v-deep .u-modal__content {
		display: flex;
		padding: 12rpx 24rpx 24rpx 24rpx;

		&>view {
			width: 100%;

		}
	}

	.slot-content {
		display: flex;
		flex-direction: column;
		align-items: center;

		.u-textarea {
			width: 90%;
			margin-top: 24rpx;
		}
	}

	.iii-box {
		#flex(-, start, center);
		#box(100%, auto, 10rpx, rgba(#8C8A8A, .2));
		#padding(12rpx 0);

		.box-item {
			#box(100%/4, auto);
			#flex(column, center, center);

			&:not(:last-child) {
				border-right: 2rpx solid rgba(#000, .1);
			}

			.box-item-title {
				#font(20rpx, #8c8a8a);
				margin-bottom: 16rpx;
			}

			.box-item-text {
				#font(24rpx, #0f0d21);
				line-height: 36rpx;
				text-align: center;
			}

			.money {
				color: #CF0000;
			}

		}
	}
</style>